import * as signalR from "@microsoft/signalr";
import { useRef, useState, useEffect, useCallback, useMemo } from 'react';
import { Button, Space, Toast, NavBar, ErrorBlock } from 'antd-mobile';
import { CloseOutline } from 'antd-mobile-icons';
import { FixedSizeList as VirtualList } from 'react-window';
import './log.less';

interface LogMessage {
  id: string;
  content: string;
  messageType: string;
  timestamp: Date;
  category:string;
}

export default function Log() {
  const [logs, setLogs] = useState<LogMessage[]>([]);
  const [otherLogs,setOtherLogs] = useState<LogMessage[]>([]);
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [connectionError, setConnectionError] = useState<string>('');
  const signalRObjRef = useRef<signalR.HubConnection | null>(null);
  const listRef = useRef<VirtualList>(null);
  const maxLogs = 100;
  const itemHeight = 48;

  // 添加日志队列，防止高频 setLogs 导致页面闪烁
  const messageQueueRef = useRef<LogMessage[]>([]);

  // 创建SignalR连接
  const createConnection = useCallback(() => {
    if (signalRObjRef.current) {
      signalRObjRef.current.stop();
    }

    // 简化连接配置
    const connection = new signalR.HubConnectionBuilder()
      .withUrl(`${process.env.API_URL || ''}/chat`)
      .build();

    // 连接开始
    connection.onreconnecting(() => {
      console.log('SignalR reconnecting');
      setIsConnected(false);
      setConnectionError('正在重新连接...');
    });

    // 连接成功
    connection.onreconnected(() => {
      console.log('SignalR reconnected');
      setIsConnected(true);
      setConnectionError('');
    });

    // 连接关闭
    connection.onclose(() => {
      console.log('SignalR connection closed');
      setIsConnected(false);
      setConnectionError('连接已断开');
    });

    // 接收消息
    connection.on('ReceiveMessage', (content: string, messageType: string = 'info',time,category = 'default') => {
      addLog(content, messageType,time,category);
    });

    signalRObjRef.current = connection;
    return connection;
  }, []);

  // 添加日志
  const addLog = useCallback((content: string, messageType: string = 'info', time?: Date,category:string="default") => {
    const newLog: LogMessage = {
      id: `${Date.now()}-${Math.random()}`,
      content,
      messageType,
      timestamp: time ? new Date(time) : new Date(),
      category,
    };
    if(category == 'low'){
      setOtherLogs(prevLogs => {
        const newLogs = [newLog, ...prevLogs];
        return newLogs.slice(0, 6);
      });
    }
    else messageQueueRef.current.push(newLog);
  }, []);

  // 启动连接
  const startConnection = useCallback(async () => {
    if (!signalRObjRef.current) return;

    try {
      setIsLoading(true);
      setConnectionError('');
      console.log('Starting SignalR connection...');
      
      await signalRObjRef.current.start();
      setIsConnected(true);
      console.log('SignalR connection started successfully');
      
      Toast.show({
        content: '日志连接成功',
        duration: 1000,
      });
    } catch (error) {
      console.error('SignalR连接失败:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      setConnectionError(`连接失败: ${errorMessage}`);
      
      Toast.show({
        content: `连接失败: ${errorMessage}`,
        duration: 3000,
      });
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 停止连接
  const stopConnection = useCallback(async () => {
    if (!signalRObjRef.current) return;

    try {
      await signalRObjRef.current.stop();
      setIsConnected(false);
      setConnectionError('');
    } catch (error) {
      console.error('停止连接失败:', error);
    }
  }, []);

  // 清空日志
  const clearLogs = useCallback(() => {
    setLogs([]);
    setOtherLogs([]);
    Toast.show({
      content: '日志已清空',
      duration: 1000,
    });
  }, []);


  // 获取日志类型样式
  const getLogTypeStyle = useCallback((messageType: string) => {
    switch (messageType) {
      case 'err':
        return 'log-error';
      case 'warn':
        return 'log-warning';
      default:
        return 'log-info';
    }
  }, []);

  // 格式化时间
  const formatTime = useCallback((date: Date) => {
    return date.toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
    });
  }, []);

  // 初始化连接
  useEffect(() => {
    const connection = createConnection();
    startConnection();

    return () => {
      stopConnection();
    };
  }, [createConnection, startConnection, stopConnection]);

  // 定时批量刷新日志
  useEffect(() => {
    const timer = setInterval(() => {
      if (messageQueueRef.current.length > 0) {
        setLogs(prevLogs => {
          const newLogs = [...messageQueueRef.current, ...prevLogs];
          messageQueueRef.current = [];
          return newLogs.slice(0, maxLogs);
        });
      }
    }, 3000); // 300ms 刷新一次
    return () => clearInterval(timer);
  }, []);

  // 自动滚动到底部
  useEffect(() => {
    if (logs.length > 0 && listRef.current) {
      listRef.current.scrollToItem(0, 'start');
    }
  }, [logs.length]);

  // 渲染日志项
  const renderLogItem = useCallback(({ index, style }: { index: number; style: React.CSSProperties }) => {
    const log = logs[index];
    if (!log) return null;

    return (
      <div style={style} className={`log-item ${getLogTypeStyle(log.messageType)}`}>
        <div className="log-time">[{formatTime(log.timestamp)}]</div>
        <div className="log-content">{log.content}</div>
      </div>
    );
  }, [logs, getLogTypeStyle, formatTime]);

  // 计算容器高度
  const containerHeight = useMemo(() => {
    return window.innerHeight - 310;
  }, []);

  return (
    <div className="log-page">
      <NavBar
        back={null}
        className="log-navbar"
        right={
          <div className="log-status">
            <span className={`status-dot ${isConnected ? 'connected' : 'disconnected'}`} />
            {isConnected ? '已连接' : '未连接'}
          </div>
        }
      >
        系统状态
      </NavBar>

      <div className="log-controls">
        <Space>
          <Button
            size="small"
            color={isConnected ? 'default' : 'primary'}
            loading={isLoading}
            onClick={isConnected ? stopConnection : startConnection}
          >
            {isConnected ? '断开连接' : '连接'}
          </Button>
          <Button
            size="small"
            color="danger"
            fill="outline"
            onClick={clearLogs}
            disabled={logs.length === 0}
          >
            <CloseOutline />
            清空消息
          </Button>
        </Space>
      </div>

      {connectionError && (
        <div className="log-error-banner">
          {connectionError}
        </div>
      )}

      <div className="log-container">
        {logs.length === 0 ? (
          <ErrorBlock status='default' title="暂无消息" description="消息需要从日本服务器同步回来，请稍等1分钟" />
        ) : (
          <>
            <div className="log-fixed">
                  {otherLogs.map(log=>{
                    return(
                      <div className={`log-item ${getLogTypeStyle(log.messageType)}`} key={log.id}>
                        <div className="log-time">[{formatTime(log.timestamp)}]</div>
                        <div className="log-content">{log.content}</div>
                      </div>
                    )
                  })}
            </div>
            <VirtualList
              ref={listRef}
              height={containerHeight}
              itemCount={logs.length}
              itemSize={itemHeight}
              width="100%"
              overscanCount={10}
            >
              {renderLogItem}
            </VirtualList>
          </>
        )}
      </div>
    </div>
  );
}